<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Refresh, Search, RefreshLeft, View, Edit, Delete, Plus } from '@element-plus/icons-vue';
import { userApi } from '../services/api';

const users = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchKeyword = ref('');

// 模态框相关状态
const showCreateModal = ref(false);
const showEditModal = ref(false);
const currentUser = ref(null);

// 表单数据
const createForm = ref({
  username: '',
  password: ''
});

const editForm = ref({
  id: null,
  password: ''
});

// 加载用户列表
const loadUsers = async () => {
  loading.value = true;
  try {
    const response = await userApi.getUsers({
      page: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchKeyword.value
    });
    users.value = response.data || [];
    total.value = response.total || 0;
  } catch (error) {
    ElMessage.error('获取用户列表失败');
    console.error('Failed to load users:', error);
  } finally {
    loading.value = false;
  }
};

// 初始加载
onMounted(() => {
  loadUsers();
});

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadUsers();
};

// 处理分页变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadUsers();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  loadUsers();
};

// 刷新列表
const handleRefresh = () => {
  loadUsers();
};

// 打开创建用户模态框
const handleOpenCreateModal = () => {
  createForm.value = {
    username: '',
    password: ''
  };
  showCreateModal.value = true;
};

// 打开编辑用户模态框
const handleOpenEditModal = (user) => {
  currentUser.value = user;
  editForm.value = {
    id: user.id,
    password: ''
  };
  showEditModal.value = true;
};

// 创建用户
const handleCreateUser = async () => {
  if (!createForm.value.username || !createForm.value.password) {
    ElMessage.warning('用户名和密码不能为空');
    return;
  }
  
  try {
    await userApi.createUser({
      username: createForm.value.username,
      password: createForm.value.password
    });
    
    ElMessage.success('用户创建成功');
    showCreateModal.value = false;
    loadUsers();
  } catch (error) {
    ElMessage.error('用户创建失败');
  }
};

// 更新用户
const handleUpdateUser = async () => {
  if (!editForm.value.password) {
    ElMessage.warning('密码不能为空');
    return;
  }
  
  try {
    await userApi.updateUser(editForm.value.id, {
      password: editForm.value.password
    });
    
    ElMessage.success('用户更新成功');
    showEditModal.value = false;
    loadUsers();
  } catch (error) {
    ElMessage.error('用户更新失败');
  }
};

// 删除用户
const handleDeleteUser = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户「${user.username}」吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await userApi.deleteUser(user.id);
    ElMessage.success('用户删除成功');
    loadUsers();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('用户删除失败');
    }
  }
};

// 检查是否为当前登录用户
const isCurrentUser = (userId) => {
  const currentUser = JSON.parse(localStorage.getItem('user'));
  return currentUser && currentUser.id === userId;
};
</script>

<template>
  <div class="user-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>账号管理</h2>
      <div>
        <el-button type="primary" @click="handleRefresh" :icon="Refresh" style="margin-right: 10px;">
          刷新
        </el-button>
        <el-button type="success" @click="handleOpenCreateModal" :icon="Plus">
          新增用户
        </el-button>
      </div>
    </div>
    
    <!-- 搜索区域 -->
    <div class="search-filter">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索用户名"
        prefix-icon="el-icon-search"
        clearable
        style="width: 300px; margin-right: 10px;"
        @keyup.enter="handleSearch"
      />
      
      <el-button @click="handleSearch" :icon="Search">
        搜索
      </el-button>
      <el-button @click="() => { searchKeyword = ''; handleSearch(); }" :icon="RefreshLeft">
        重置
      </el-button>
    </div>
    
    <!-- 用户列表 -->
    <el-table
      v-loading="loading"
      :data="users"
      stripe
      border
      style="width: 100%; margin-top: 20px;"
      empty-text="暂无用户数据"
    >
      <el-table-column prop="id" label="用户ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名" width="180"></el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180">
        <template #default="{ row }">
          {{ new Date(row.created_at).toLocaleString('zh-CN') }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right">
        <template #default="{ row }">
          <el-button type="info" text :icon="View" @click="handleOpenEditModal(row)" style="margin-right: 5px;">
            编辑
          </el-button>
          <el-button 
            type="danger" 
            text 
            :icon="Delete" 
            @click="handleDeleteUser(row)" 
            :disabled="isCurrentUser(row.id)"
            style="margin-left: 5px;"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 创建用户模态框 -->
    <el-dialog
      v-model="showCreateModal"
      title="新增用户"
      width="500px"
    >
      <el-form
        :model="createForm"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="createForm.username"
            placeholder="请输入用户名"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="createForm.password"
            type="password"
            placeholder="请输入密码"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateModal = false">取消</el-button>
          <el-button type="primary" @click="handleCreateUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 编辑用户模态框 -->
    <el-dialog
      v-model="showEditModal"
      title="编辑用户"
      width="500px"
    >
      <el-form
        :model="editForm"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input
            :value="currentUser?.username"
            disabled
          />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="editForm.password"
            type="password"
            placeholder="请输入新密码"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditModal = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-management {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.search-filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-filter {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-filter .el-input {
    width: 100%;
    margin-right: 0;
  }
  
  .pagination {
    justify-content: center;
  }
}
</style>